<?php

namespace app\controller\backend;

use app\model\SeoAccount;
use app\validate\SeoAccountValidate;
use think\exception\ValidateException;
use think\response\Json;

/**
 * SEO账号灌管理
 */
class SeoAccountController extends BaseController
{

    public function lists(SeoAccount $seoModel): Json
    {
        $limit = input('param.limit');
        $where = [];

        $list = $seoModel->getAccountList($where, $limit);
        return json(pageReturn($list));
    }

    public function add(SeoAccount $seoModel): Json
    {
        $param = input('post.');

        $has = $seoModel->field('id')->where('account', $param['account'])->find();
        if (!empty($has)) {
            return jsonReturn(-2, lang('该账号已经存在'));
        }

        try {

            validate(SeoAccountValidate::class)->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $param['create_time'] = date('Y-m-d H:i:s');

        $seoModel->insert($param);
        return jsonReturn(0, lang('添加账号成功'));
    }

    public function info(SeoAccount $seoModel): Json
    {
        $info = $seoModel->where('id', input('param.id'))->find();
        return jsonReturn(0, lang('查询成功'), $info);
    }

    public function edit(SeoAccount $seoModel): Json
    {
        $param = input('post.');

        $has = $seoModel->field('id')->where('account', $param['account'])->where('id', '<>', $param['id'])->find();
        if (!empty($has)) {
            return jsonReturn(-2, lang('该账号已经存在'));
        }

        try {
            validate(SeoAccountValidate::class)->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $param['update_time'] = date('Y-m-d H:i:s');

        $seoModel->where('id', $param['id'])->update($param);
        return jsonReturn(0, lang('编辑账号成功'));
    }

    public function del(SeoAccount $seoModel)
    {
        $seoModel->where('id', input('param.id'))->delete();

        return jsonReturn(0, lang('删除成功'));
    }
}